package com.gdth.core.widget;

import java.util.ArrayList;
import java.util.List;

import com.gdth.utils.BaseAppUtil;
import com.gdth.utils.TimerInstance;

import android.app.Activity;
import android.app.Application;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.Intent.ShortcutIconResource;
import android.content.SharedPreferences.Editor;
import android.content.res.Configuration;
import android.os.Handler;
import android.os.Message;
import android.widget.Toast;

public class BaseApplication extends Application{
	public static String TAG = "Application";
	private static final String Application_Name = "application";
	private static final String Guide_First = "Guide_First";
	public static final String OS_MODEL = "OS_MODEL";
	public static final String OS_VERSION_SDK = "OS_VERSION_SDK";
	public static final String OS_VERSION_RELEASE = "OS_VERSION_RELEASE";
	
	public static String versionName;
	public static int versionCode;
	public static String SDCardPath;
	
	public boolean isLogin = false;
	
	public boolean mFirst;

	public boolean isLanchs = false;
	
	private static BaseApplication mAppApplication;
	
	@Override
	public void onCreate() {
		versionCode = BaseAppUtil.getVerCode(getApplicationContext());
		versionName = BaseAppUtil.getVerName(getApplicationContext());
		SDCardPath = BaseAppUtil.getSDCardPath();
		
		mFirst = isFirstEnter();
		
		//添加
//		BaseApplication appState = (BaseApplication)getApplicationContext(); 
//		appState.addActivity(this);
		//结束代码
//		MyApp appState = (MyApp)getApplicationContext(); 
//		appState .finishAll() 
		
		TimerInstance.getInstance().CreateTask(exitHandler);
		TimerInstance.getInstance().setTimeout(30);
	}
	
	/**
	 * 程序终止的时候执行
	 */
	@Override
	public void onTerminate() {
		super.onTerminate();
	}
	
    @Override
    public void onLowMemory() {
        // 低内存的时候执行
        super.onLowMemory();
    }
    
    @Override
    public void onTrimMemory(int level) {
        // 程序在内存清理的时候执行
        super.onTrimMemory(level);
    }
    
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }
	
	
	/**********************公用方法**************************/
	/**
	 * 判断是否第一次运行
	 * @return
	 */
	public boolean isFirstEnter(){
		SharedPreferences system_info = getSharedPreferences(Application_Name, 0);
		String mResultStr = system_info.getString(Guide_First, "");
		if(mResultStr.equalsIgnoreCase("")){
			Editor editor = system_info.edit();
  		  	editor.putString(Guide_First, "false");
  		  	editor.putString(OS_MODEL, BaseAppUtil.getModelForOS());
  		  	editor.putString(OS_VERSION_SDK, String.valueOf(BaseAppUtil.getVersionSDKForOS()));
  		  	editor.putString(OS_VERSION_RELEASE, BaseAppUtil.getVersionReleaseForOS());
  		  
  		  	editor.commit();
  		  	
			return true;
		}
		else
			return false;
	}
	
	/**
	 * 添加桌面快捷方式
	 * @param app_name
	 * @param ActivityName
	 * @param ic_launcher
	 */
	public void addDesktopMenu(String app_name, String ActivityName, int ic_launcher){  
		Intent shortcut = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");
		/*以下两句是为了在卸载应用的时候同时删除桌面快捷方式*/  
		shortcut.setAction("android.intent.action.MAIN");    
		shortcut.addCategory("android.intent.category.LAUNCHER");
		// 快捷方式的名称
		shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, app_name);
		// 不允许重复创建
		shortcut.putExtra("duplicate", false);

		// 指定当前的Activity为快捷方式启动的对象: 如 com.everest.video.VideoPlayer
		// 这里必须为Intent设置一个action，可以任意(但安装和卸载时该参数必须一致)
		String action = this.getPackageName() + ".SplashScreenActivity";
		Intent mIntent = new Intent();
		mIntent.setClassName(this, ActivityName);
		mIntent.setAction(action);
		shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, mIntent);
		// 下面的方法与上面的效果是一样的,另一种构建形式而已
		// 注意: ComponentName的第二个参数必须加上点号(.)，否则快捷方式无法启动相应程序
		// String appClass = this.getPackageName() + "." + this.getLocalClassName();
		// ComponentName comp = new ComponentName(this.getPackageName(), appClass);
		// shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, new Intent(action).setComponent(comp));

		// 快捷方式的图标
		ShortcutIconResource iconRes = Intent.ShortcutIconResource.fromContext(this, ic_launcher);
		shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconRes);

		sendBroadcast(shortcut);
    }
	
	private Handler exitHandler = new Handler(new Handler.Callback() {
		
		@Override
		public boolean handleMessage(Message msg) {
			// TODO Auto-generated method stub
			
			int type = msg.what;
			if (type == 1) {
//				int time = msg.getData().getInt("time");
//				int min = time / 60;
//	        	int second = time % 60;
//	        	
//	        	String timer_s = "";
//	        	if (min < 10) timer_s = "0" + min + ":";
//	        	else timer_s = min + ":";
//	        	
//	        	if (second < 10) timer_s += "0" + second;
//	        	else timer_s += second;
			} else if (type == 2) {
				Toast.makeText(getApplicationContext(), "超时", Toast.LENGTH_SHORT).show();
				
				BaseApplication.getApp().finishAll();
			}
			return false;
		}
	});
	
	/** 获取Application */  
    public static BaseApplication getApp() {  
        if (mAppApplication == null) {  
            mAppApplication = new BaseApplication();  
        }  
        return mAppApplication;  
    } 
	
	public List<Activity> activityList;
	
	public void addActivity(Activity acitivity) { 
		if(activityList == null){  
            activityList = new ArrayList<Activity>();  
        }
		
        activityList.add(acitivity); 
	}
	
	/** 清空列表，取消引用*/  
    public void clearActivity(){  
        activityList.clear();  
    }
	
    /** 遍历退出所有Activity */  
    public void exit() {  
        for(Activity activity : activityList) {  
            activity.finish();  
        }  
        clearActivity();//千万记得清空取消引用。  
        System.exit(0);  
    } 
    
	/**
	 * 退出所有activity
	 */
	public void finishAll() {
		if (isLogin) {
			for(Activity act : activityList) { 
				if(!act.isFinishing()){ 
					act.finish(); 
				} 
			} 
			activityList = null;
			isLogin = false;
			try {
				final Intent intent = getPackageManager().getLaunchIntentForPackage(getPackageName());  
		        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);  
		        startActivity(intent);  
			}catch(NullPointerException e) {
				
			}
		}
	} 
}
